package com.powernode.common.utils;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.powernode.common.constant.JWTConstants;

import java.util.HashMap;
import java.util.Map;

public class JwtUtils {
    /**
     * 创建jwt
     * @param data
     * @return
     */
    public static String createJwt(Object data) {
        Map<String, Object> map = new HashMap<>();
        map.put(JWTConstants.JWT_ALG,JWTConstants.JWT_ALG_VALUE);
        map.put(JWTConstants.JWT_TYP, JWTConstants.JWT_TYP_VALUE);
        return JWT.create()
                .withHeader(map)
                .withClaim("user", JSONObject.toJSONString(data))
                .sign(Algorithm.HMAC256(JWTConstants.JWT_SECRET));
    }

    /**
     * 验证jwt是否正确
     * @param jwt
     * @return
     */
    public static boolean verifyJwt(String jwt) {
        try {
            JWT.require(Algorithm.HMAC256(JWTConstants.JWT_SECRET)).build().verify(jwt);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 解析jwt
     * @param jwt
     * @return
     */
    public static Object parseJwt(String jwt) {
        return JWT.decode(jwt).getClaim("user").asString();
    }
}
